package com.ophiux.cs.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ophiux.cs.application.consultOrder.dto.GetCSOrderRecordsDetailRequest;
import com.ophiux.cs.application.consultOrder.dto.GetCSOrderRecordsDetailResponse;
import com.ophiux.cs.application.consultOrder.service.IGetCSOrderRecordsDetailAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.utils.common.DateUtil;
import com.ophiux.utils.common.StringUtil;
import com.ophiux.utils.parser.json.JsonUtils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

/**
 * 说明：前端上传图片到服务器<br>
 * <h1>创 建 人: hehailong<br></h1>
 * 创建日期: 2018年9月28日 下午3:21:16<br>
 * 修改记录：
 */
@Controller
@Slf4j
@RequestMapping(value = "/upload")
public class ImgUploadController {
	private final static String ENCODE = "UTF-8";
	@Autowired
	IGetCSOrderRecordsDetailAppService getCSOrderRecordsDetailAppService;
	
	@Value("${ophiux.img.url}")
	private String imgUrl;


	@RequestMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@ResponseBody
	public String uploadImg(@RequestParam("file") MultipartFile[] files) {
		Result<String> result = new Result<>();
		String imgPath = "";// 存入数据库图片路径
		try {
			for (MultipartFile file : files) {
				if (!"image/jpeg".equals(file.getContentType()) && !"image/png".equals(file.getContentType())) {
					continue;
				}
				log.info(" file name = " + file.getOriginalFilename() + ", file size = " + file.getSize());
				String date = DateUtil.getCurrentDate("yyyyMMdd");
				String newPath = keepUploadImg(file, "upload/" + date + "/", "webp", "jpg");
//				imgPath = imgPath + newPath + ",";
				imgPath = imgPath + newPath;
//				return imgPath;
			}
			
			result = Result.success(imgPath);
		} catch (Exception e) {
			e.printStackTrace();
			result = Result.fail(ResultEnum.UploadImgException);
		}
		return JsonUtils.toJson(result);
	}

	/**
	 * 保存图片到磁盘
	 * @param file
	 * @param code
	 * @param zipFileType
	 * @param sourceFileType
	 * @return
	 */
	public String keepUploadImg(MultipartFile file, String code, String zipFileType, String sourceFileType) throws Exception {
		String newFilePath = "";
		try {
			String filePath = imgUrl+ code;
			// 获取操作时间
			String dateString = DateUtil.getCurDateRandom();
			// 获取毫秒
			long t1 = System.currentTimeMillis();
			File dir = new File(filePath);
			if (!dir.exists())
				dir.mkdirs();
			// 文件夹--存放压缩图片
			File dirzip = new File(filePath + "/ZIP");
			if (!dirzip.exists())
				dirzip.mkdirs();
			// 拼接唯一文件名
			String newFileName = dateString + t1;
			File tagetFile = new File(filePath + "/" + newFileName + "." + sourceFileType);// 创建文件对象
			FileOutputStream output = new FileOutputStream(filePath + "/ZIP/" + newFileName + "." + zipFileType);
			if (!tagetFile.exists()) {// 文件名不存在 则新建文件，并将文件复制到新建文件中
				try {
					tagetFile.createNewFile();
					file.transferTo(tagetFile);
					// 压缩文件
					// Thumbnails.of(filePath+"/"+newFileName+"."+sourceFileType).size(100,
					// 100).toFile(filePath+"/ZIP/"+newFileName+".webp" );
					Thumbnails.of(filePath + "/" + newFileName + "." + sourceFileType).scale(0.5)
							.toOutputStream(output);
					output.flush();
					output.close();
//					newFilePath = getURLEncoderString(filePath + "/ZIP" + "/" + newFileName + "." + zipFileType);
					newFilePath = filePath + "/ZIP" + "/" + newFileName + "." + zipFileType;
				} catch (Exception e) {
					output.flush();
					output.close();
					e.printStackTrace();
				}
			}
			return newFilePath;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("上传图片异常,异常信息", e);
			throw new Exception();
		}
	}

	/**
	 * 获取图片页面展示
	 * @param imgPath
	 */
	@RequestMapping(value = "/getImg")
	public void getImg(HttpServletRequest request, HttpServletResponse response,@RequestParam("imgPath") String imgPath) {
		String moWeiFilePath = getURLDecoderString(imgPath);
		String filePath = moWeiFilePath;
		FileInputStream inputStream = null;
		OutputStream out = null;
		try {
			inputStream = new FileInputStream(filePath);
			int i = inputStream.available();
			byte[] buff = new byte[i];
			inputStream.read(buff);
			inputStream.close();
			response.setContentType("image/*");
			out = response.getOutputStream();
			out.write(buff);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取图片异常，异常信息:",e);
		}
	}
	public static void main(String[] args) {
		String url = "";
		String[] urls = url.split(",");
		int length = urls.length;
		System.out.println(length);
		
	}
	/**
	 * 获取图片页面展示
	 * @param ID
	 * @param INDEX
	 * @param USER_ID
	 */
	@RequestMapping(value = "/getImg1")
	public void getImg(HttpServletRequest request, HttpServletResponse response) {
		try {
			FileInputStream inputStream = null;
			OutputStream out = null;
			String id = request.getParameter("ID");//记录id
			String index = request.getParameter("INDEX");//图片索引
			String userId = request.getParameter("USER_ID");//用户id
			GetCSOrderRecordsDetailRequest req = new GetCSOrderRecordsDetailRequest();
			req.setRECORD_ID(id);
			req.setUSER_ID(userId);
			
			Result<GetCSOrderRecordsDetailResponse> result = getCSOrderRecordsDetailAppService.GetCSOrderRecordsDetail(req);
			if(result.isSuccess()) {
				String url = result.getRESPONSE().getRECORD_DESCRIPTION().getIMG_URLS();
				if(!StringUtil.isEmpty(url)) {
					String[] urls = url.split(",");
					if(!StringUtil.isEmpty(index)) {//如果索引不为空，则返回索引对应的图片
						int ind = Integer.parseInt(index);
						String moWeiFilePath = getURLDecoderString(urls[ind]);
						inputStream = new FileInputStream(moWeiFilePath);
						int i = inputStream.available();
						byte[] buff = new byte[i];
						inputStream.read(buff);
						inputStream.close();
						response.setContentType("image/*");
						out = response.getOutputStream();
						out.write(buff);
						out.flush();
						out.close();
						
					}else {//则直接返回图片数量
						Result<String> resultResp = new Result<>();
						response.setContentType("text/html; charset=UTF-8");
						PrintWriter print = response.getWriter();
						int length = 0;
						length = urls.length;
						resultResp = Result.success(length+"");
						print.println(JsonUtils.toJson(resultResp));
						print.flush();
						print.close();
					}
					
				}else {
					log.info("不存在咨询图片。。。。");
				}
				
			}else {
				log.info("查询咨询记录"
						+ "数据失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取图片异常，异常信息:",e);
		}
	}

	/**
	 * 删除图片
	 * @param imgPath
	 * @return
	 */
	@RequestMapping(value = "/deleteImg")
	public boolean doRmoeve(@RequestParam("imgPath") String imgPath) {
		String moWeiFilePath = getURLDecoderString(imgPath);
		String[] sourceFilePathS = moWeiFilePath.split("/");
		String sourceFilePath = sourceFilePathS[0];
		for (int i = 1; i < sourceFilePathS.length - 2; i++) {
			sourceFilePath = sourceFilePath + "/" + sourceFilePathS[i];
		}
		sourceFilePath = sourceFilePath + "/" + sourceFilePathS[sourceFilePathS.length - 1];
		File fileZip = new File(moWeiFilePath);
		File sourceFileZip = new File(sourceFilePath);
		try {
			if (fileZip.exists()) {
				if (fileZip.isFile()) {
					// 删除压缩文件
					fileZip.delete();
				}
			}
			if (sourceFileZip.exists()) {
				if (sourceFileZip.isFile()) {
					// 删除源文件
					sourceFileZip.delete();
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * URL 转码
	 * 
	 * @return
	 */
	public static String getURLEncoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLEncoder.encode(str, ENCODE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * URL 解码
	 */
	public static String getURLDecoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLDecoder.decode(str, ENCODE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
